package des

import (
	"bytes"
	"crypto/des"
	"encoding/base64"
	"github.com/gogf/gf/frame/g"
)

//DES加密,ECB模式
func EncryptDesECB(data, key []byte) string {
	if len(key) > 8 {
		key = key[:8]
	}
	block, err := des.NewCipher(key)
	if err != nil {
		g.Log().Errorf("EncryptDesECB newCipher error[%v]\n", err)
		return ""
	}
	bs := block.BlockSize()
	data = PKCS5Padding(data, bs)
	if len(data)%bs != 0 {
		g.Log().Error("EncryptDesECB Need a multiple of the block size")
		return ""
	}
	out := make([]byte, len(data))
	dst := out
	for len(data) > 0 {
		block.Encrypt(dst, data[:bs])
		data = data[bs:]
		dst = dst[bs:]
	}
	return base64.StdEncoding.EncodeToString(out)
}
func DecryptDESECB(d, key []byte) string {
	data, err := base64.StdEncoding.DecodeString(string(d))
	if err != nil {
		g.Log().Errorf("DecryptDESECB Decode base64 error[%v]\n", err)
		return ""
	}
	if len(key) > 8 {
		key = key[:8]
	}
	block, err := des.NewCipher(key)
	if err != nil {
		g.Log().Errorf("DecryptDESECB NewCipher error[%v]\n", err)
		return ""
	}
	bs := block.BlockSize()
	if len(data)%bs != 0 {
		g.Log().Error("DecryptDES crypto/cipher: input not full blocks")
		return ""
	}
	out := make([]byte, len(data))
	dst := out
	for len(data) > 0 {
		block.Decrypt(dst, data[:bs])
		data = data[bs:]
		dst = dst[bs:]
	}
	out = PKCS5UnPadding(out)
	return string(out)
}

func PKCS5Padding(ciphered []byte, blockSize int) []byte {
	padding := blockSize - len(ciphered)%blockSize
	paddingtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphered, paddingtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
